package secondriver.process;


import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.eclipse.jetty.util.UrlEncoded;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import secondriver.process.core.Setting;
import secondriver.process.core.cache.DiskCache;
import secondriver.process.core.cache.DoubleLevelCache;
import secondriver.process.core.cache.MemoryCache;
import secondriver.process.core.source.PathSource;
import secondriver.process.core.source.SourceManager;
import secondriver.process.core.source.UrlSource;
import secondriver.process.exception.ClientRequestException;
import secondriver.process.exception.ServerInnerException;
import secondriver.process.exception.SettingException;
import secondriver.process.handler.ImageProcess;

import static spark.Spark.*;

/**
 * Author : secondriver
 * Date :  2015/12/28
 */
public final class ImageProcessService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImageProcessService.class);

    private ImageProcessService() {
    }

    public static void main(String[] args) throws IOException {

        //读配置信息
        final Setting setting;
        try {
            if (args.length >= 1) {
                Path path = Paths.get(args[0]);
                String settingFile = path.normalize().toAbsolutePath().toString();
                setting = Setting.create(settingFile);
            } else {
                setting = Setting.create();
            }
        } catch (SettingException e) {
            LOGGER.error("Setting exception, please check it and then rerun . \nDetail: " + e.getMessage());
            return;
        }

        //配置服务
        port(setting.getPort());
        staticFileLocation(setting.getStaticFileLocation());
        externalStaticFileLocation(setting.getExternalStaticFileLocation());
        threadPool(
                setting.getMaxThreads(),
                setting.getMinThreads(),
                setting.getThreadIdleTimeoutMillis()
        );
        if (setting.isSecureSupported()) {
            secure(
                    setting.getKeystoreFile(),
                    setting.getKeystorePassword(),
                    setting.getTruststoreFile(),
                    setting.getTruststorePassword()
            );
        }
        LOGGER.info(setting.toString());

        //添加源支持
        SourceManager.addSource(new UrlSource());
        SourceManager.addSource(new PathSource(setting.getExternalStaticFileLocation()));

        //业务处理
        /**
         * 支持：
         * 尺寸缩放，比例缩放，裁剪，旋转，水印
         */
        ImageProcess imageProcess = new ImageProcess(setting);
        imageProcess.setCache(
                new DoubleLevelCache(
                        new MemoryCache(setting.getMaxCache()),
                        new DiskCache(setting.getCacheFileLocation()))
        );

        final String compositionApi = "/composition";
        before(compositionApi, (request, response) -> {
            StringBuilder reqInfo = new StringBuilder(":{")
                    .append("\n\trequestMethod:  ").append(request.requestMethod())
                    .append("\n\tcontextPath:    ").append(request.contextPath())
                    .append("\n\tqueryString:    ").append(UrlEncoded.decodeString(request.queryString()))
                    .append("\n}");
            LOGGER.info(reqInfo.toString());
        });
        get(compositionApi, imageProcess);


        //异常处理
        exception(ClientRequestException.class, new ClientRequestException());
        exception(ServerInnerException.class, new ServerInnerException());
    }
}